package com.future.lock.me.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.future.baselib.activity.BaseActivity;
import com.future.baselib.entity.MessageEvent;
import com.future.baselib.utils.EventBusUtil;
import com.future.baselib.utils.PatternUtils;
import com.future.baselib.utils.UserInfoSharePreference;
import com.future.lock.R;
import com.future.lock.common.Constants;
import com.future.lock.common.MyApp;
import com.future.lock.common.http.HttpUtils;
import com.future.lock.common.http.response.DefaultHttpResponse;
import com.future.lock.me.entity.response.LoginResponse;
import com.igexin.sdk.PushManager;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginActivity extends BaseActivity implements PlatformActionListener {

    public static final String TAG = LoginActivity.class.getName();

    @BindView(R.id.iv_left)
    ImageView ivLeft;
    @BindView(R.id.view_line)
    View viewLine;
    @BindView(R.id.et_mobile)
    EditText etMobile;
    @BindView(R.id.btn_getCode)
    Button btnGetCode;
    @BindView(R.id.et_code)
    EditText etCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected void initContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
    }

    @Override
    protected void initView() {
        viewLine.setVisibility(View.GONE);
        ivLeft.setImageResource(R.mipmap.ic_exit);
    }

    @Override
    protected void initLogic() {

    }

    @Override
    protected void getBundleExtras(Bundle extras) {

    }

    @OnClick({R.id.tv_login, R.id.tv_wechat, R.id.tv_register_protocol, R.id.btn_getCode})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_getCode:
                getCode();
                break;
            case R.id.tv_login:
                login();
                break;
            case R.id.tv_wechat:
                Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
                wechat.setPlatformActionListener(this);
                wechat.authorize();
                break;
            case R.id.tv_register_protocol:
                startActivity(RegisterProtocolActivity.class);
                break;
        }
    }

    private void login() {
        final String mobile = etMobile.getText().toString().trim();
        if (!PatternUtils.mobilePattern(toast, mobile)) {
            return;
        }
        String code = etCode.getText().toString().trim();
        if (TextUtils.isEmpty(code)) {
            toast("验证码不能为空");
            return;
        }
        if (code.length() < 4) {
            toast("请正确输入验证码");
            return;
        }

        HttpUtils.getHttpApi()
                .login(mobile, code, PushManager.getInstance().getClientid(this),
                        "", "", "", "1")
                .enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {
                        LoginResponse loginResponse = new LoginResponse();
                        loginResponse.parse(response.body());
                        toast(loginResponse.msg);
                        if (loginResponse.success == 1) {//请求成功
                            UserInfoSharePreference.getInstance(LoginActivity.this).setUserToken(loginResponse.loginBean.user_token);
                            MyApp.setUserToken(loginResponse.loginBean.user_token);
                            MyApp.setUserInfo(loginResponse.loginBean);
                            EventBusUtil.sendEvent(new MessageEvent(Constants.REFRESH_LOCK_DATA));
                            finish();
                        }
                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable t) {
                        toast(t.getMessage());
                    }
                });
    }

    @SuppressWarnings("unchecked")
    private void getCode() {
        String mobile = etMobile.getText().toString().trim();
        if (!PatternUtils.mobilePattern(toast, mobile)) {
            return;
        }
        btnGetCode.setClickable(false);
        HttpUtils.getHttpApi().getCode(mobile).enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                DefaultHttpResponse defaultResponse = new DefaultHttpResponse();
                defaultResponse.parse(response.body());
                toast(defaultResponse.msg);
                if (defaultResponse.success == 1) {//请求成功
                    new Thread(runnable).start();
                    toast("验证码已发送");
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                toast(t.getMessage());
            }
        });
    }


    //验证码发送倒计时
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            runOnUiThread(() -> btnGetCode.setClickable(false));
            for (int i = 60; i > 0; i--) {
                final int finalI = i;
                runOnUiThread(() -> btnGetCode.setText("重新获取(" + finalI + ")"));
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            runOnUiThread(() -> {
                btnGetCode.setClickable(true);
                btnGetCode.setText("重新获取");
            });
        }
    };

    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
        final String token = platform.getDb().getUserId();
        final String userIcon = platform.getDb().getUserIcon();
        final String userName = platform.getDb().getUserName();
//        String os = new StringBuilder().append("wechatToken:").append(token)
//                .append("\nclientId:").append(PushManager.getInstance().getClientid(this))
//                .append("\nos:").append("1").toString();
//        Log.e(TAG, os);
        HttpUtils.getHttpApi()
                .wechatLogin(token, PushManager.getInstance().getClientid(this), "1").enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                LoginResponse loginResponse = new LoginResponse();
                loginResponse.parse(response.body());
                if (loginResponse.success == 1) {//请求成功
                    if (TextUtils.isEmpty(loginResponse.data)||TextUtils.equals(loginResponse.data,"null")) {
                        Bundle bundle = new Bundle();
                        bundle.putString(BindingPhoneActivity.WECHAT_TOKEN, token);
                        bundle.putString(BindingPhoneActivity.WECHAT_ICON, userIcon);
                        bundle.putString(BindingPhoneActivity.WECHAT_NAME, userName);
                        startActivity(BindingPhoneActivity.class, bundle);
                    }else{
                        UserInfoSharePreference.getInstance(LoginActivity.this).setUserToken(loginResponse.loginBean.user_token);
                        MyApp.setUserToken(loginResponse.loginBean.user_token);
                        MyApp.setUserInfo(loginResponse.loginBean);
                        EventBusUtil.sendEvent(new MessageEvent(Constants.REFRESH_LOCK_DATA));
                        finish();
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                toast(t.getMessage());
            }
        });
    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {
        toast(throwable.getMessage());
    }

    @Override
    public void onCancel(Platform platform, int i) {
        toast("微信登录取消");
    }
}
